const Koa= require('koa')
const router = require('koa-router')()
const bodyparser = require('koa-bodyparser');
const app = new Koa();
const query = require('./db/query')
//查询
router.get('/list',async ctx=>
{
    let res=await query(`select * from login`);
    ctx.body={
        code:0,
        data:res,
        mes:"list接口",
    }
    
})
//添加
router.post('/add',async ctx=>
{
    let {name,phone,pwd}=ctx.request.body;
    const res=await query(`insert into login (name,phone,pwd) values ('${name}','${phone}','${pwd}')`);
    if(res.affectedRows == 1)
    {
        ctx.body={
            code:0,
            data:res,
            mes:"添加成功",
        }
    }
    else
    {
        ctx.body={
            code:1,
            mes:"添加失败",
        }
    }
})
//修改
router.post('/update',async ctx=>
{
    let {name,phone,pwd,id}=ctx.request.body;
    const res=await query(`update login set name='${name}',
    phone='${phone}',pwd='${pwd}' 
    where id=${id}`);
    if(res.affectedRows == 1)
    {
        ctx.body={
            code:0,
            data:res,
            mes:"修改成功",
            
        }
    }
    else
    {
        ctx.body={
            code:1,
            mes:"修改失败",
        }
    }
})
//删除
router.get('/delete',async ctx=>
{
    let {id}=ctx.query;
    let res=await query(`delete  from login where id=${id}`);
    if(res.affectedRows == 1)
    {
        ctx.body={
            code:0,
            mes:"删除成功",
            res
        }
    }
    else
    {
        ctx.body={
            code:1,
            mes:"删除失败",
        }
    }
})
app.use(bodyparser())
app.use(router.routes());
app.use(router.allowedMethods())
app.listen(3000)